<?php
declare (strict_types = 1);

namespace app\common\listener;

use think\facade\Cache;

class CheckAuth
{
    /**
     * 事件监听处理
     *
     * @return mixed
     */
    public function handle($event)
    {
        $params = $event;
        /*防止跨域*/
        // header('Access-Control-Allow-Origin: '.$_SERVER['HTTP_ORIGIN']);
        header('Access-Control-Allow-Origin:*');
        header('Access-Control-Allow-Credentials: true');
        header('Access-Control-Allow-Methods:GET,PUT,POST,DELETE,OPTIONS');
        header('Access-Control-Allow-Headers:*');
        $request = request();
        $m = strtolower(\think\facade\App::initialize()->http->getName());
        $c = strtolower($request->controller());
        $a = strtolower($request->action());
        //提交方式拦截
        // $scan = new \com\Scan();
        // $response = $scan->webscan_Check();

        $allow = $params['allow']; //登录用户可访问
        $permission = $params['permission']; //无限制

        /*获取头部信息*/
        $header   = $request->header();
        $authKey  = isset($header['auth-key']) && $header['auth-key'] ? trim($header['auth-key']) : '';
        $paramArr = $request->param();
        $cache = Cache::get('auth:'.$authKey);
        $userInfo = $cache['userInfo'] ?? [];
        if (in_array($a, $permission)) {
            return true;
        }
//        if (empty($userInfo['id'])) {
//            header('Content-Type:application/json; charset=utf-8');
//            exit(json_encode(['code'=>401,'msg'=>'请先登录']));
//        }
//        if ($userInfo['id'] == 1) {
//            return true;
//        }
//        if (in_array($a, $allow)) {
//            return true;
//        }
//        //管理员角色
//        $adminTypes = adminGroupTypes($userInfo['id']);
//        if (in_array(1,$adminTypes)) {
//            return true;
//        }
//
//        //操作权限
//        $res_per = checkPerByAction($m, $c, $a);
//        if (!$res_per) {
//            header('Content-Type:application/json; charset=utf-8');
//            exit(json_encode(['code'=>403,'msg'=>'无权操作']));
//        }
    }
}
